package com.son.hotel.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.son.hotel.common.ErrorCode;
import com.son.hotel.common.Result;
import com.son.hotel.domain.RoomType;
import com.son.hotel.domain.Rooms;
import com.son.hotel.execption.BusinessException;
import com.son.hotel.response.RoomDetailInfoResp;
import com.son.hotel.service.RoomTypeService;
import com.son.hotel.service.RoomsService;
import com.son.hotel.vo.SearchInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@Tag(name = "房间类型信息")
@CrossOrigin(origins = {"http://localhost:8081"},allowCredentials = "true")
@RequestMapping("/menu")
public class RoomTypeController {

    @Autowired
    private RoomTypeService roomTypeService;

    @Autowired
    private RoomsService roomsService;

    /**
     *查询所有房间的型号
     * @return
     */
    @Operation(summary = "查询所有房间信息")
    @GetMapping("/list")
    public Result<List<RoomType>> listAllRoomType(){
        List<RoomType> list = roomTypeService.list();
        if (CollectionUtil.isEmpty(list)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"列表为空");
        }
        return Result.success("200",list);
    }

    /**
     * 查询所有房间具体信息(admin)
     * @return
     */
    @Operation(summary = "房间管理-查询-admin")
    @GetMapping("/roomInfo/list")
    public Result<List<RoomDetailInfoResp>> listAllRoomInfo(){

        List<Rooms> roomList = roomsService.list();
        List<RoomType> roomTypeList = roomTypeService.list();

        List<RoomDetailInfoResp> roomDetailInfoResp = roomTypeService.listAllRoomInfo(roomList, roomTypeList);
        return Result.success("200",roomDetailInfoResp);
    }

    /**
     * 修改房间的具体信息(admin)
     * @return
     */
    @Operation(summary = "房间管理-修改-admin")
    @PostMapping("/roomInfo/update")
    public Result<ErrorCode> updateRoomInfo(@RequestBody RoomDetailInfoResp roomDetailInfoResp){
        if (BeanUtil.isEmpty(roomDetailInfoResp)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"参数为空");
        }
        log.info("roomDetailInfo:{}",roomDetailInfoResp);
        int id = roomDetailInfoResp.getRoomId();
        UpdateWrapper<Rooms> wrapper = new UpdateWrapper<>();
        wrapper.set("status",roomDetailInfoResp.getStatus()).eq("id",id);
        boolean result = roomsService.update(wrapper);

        //查询typeId
        Rooms rooms = roomsService.getById(id);
        Integer typeId = rooms.getTypeId();
        UpdateWrapper<RoomType> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .set("name",roomDetailInfoResp.getRoomName())
                .set("price",roomDetailInfoResp.getPrice())
                .eq("id",typeId);
        roomTypeService.update(updateWrapper);
        return Result.success(ErrorCode.SUCCESS);
    }

    /**
     * 删除房间的信息
     * @param roomId
     * @return
     */
    @Operation(summary = "房间管理-删除-admin")
    @DeleteMapping("/roomInfo/delete/{roomId}")
    public Result<ErrorCode> deleteRoomInfo(@PathVariable int roomId){
        if (roomId <= 0){
            throw new BusinessException(ErrorCode.PARAMETER_ERROR);
        }
        Rooms rooms = roomsService.getById(roomId);
        if (rooms.getStatus() != 0 ){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"房间已住，无法删除");
        }
        boolean result = roomsService.removeById(roomId);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除错误");
        }
        //让roomType中的数量减一
        roomTypeService.updateRoomTypeInfoDec(rooms.getTypeId());
        return Result.success("200",ErrorCode.SUCCESS);
    }

    /**
     * 添加房间的信息
     * @param roomDetailInfoResp
     * @return
     */
    @Operation(summary = "房间管理-添加-admin")
    @PostMapping("/roomInfo/add")
    public Result<ErrorCode> addRoomInfo(@RequestBody RoomDetailInfoResp roomDetailInfoResp){
        log.info("roomDetailInfoResp:{}",roomDetailInfoResp);
        //TODO 向room表添加数据
        Rooms rooms = new Rooms();
        rooms.setId(roomDetailInfoResp.getRoomId());
        rooms.setStatus(0);
        String roomName = roomDetailInfoResp.getRoomName();
        //强转类型String->int
        Integer typeId = Convert.toInt(roomName);
        rooms.setTypeId(typeId);
        boolean save = roomsService.save(rooms);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"添加失败");
        }
        //TODO 让roomType表数量加一
        roomTypeService.updateRoomTypeInfoInc(typeId);
        return Result.success("200",ErrorCode.SUCCESS);
    }

    /**
     * 搜索房间
     * @param searchInfo
     * @return
     */
    @Operation(summary = "房间管理-搜索-admin")
    @PostMapping("/roomInfo/search")
    public Result<List<RoomDetailInfoResp>> searchRoom(@RequestBody SearchInfo searchInfo){
        // 验证字段合法性
        if (!Arrays.asList("类型", "状态", "房号").contains(searchInfo.getKey())) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR);
        }
        List<RoomDetailInfoResp> roomDetailInfoResp = roomTypeService.searchRoom(searchInfo);
        return Result.success("200",roomDetailInfoResp);
    }

    /**
     * 批量导出
     * @param name
     */
    @Operation(summary = "房间管理-导出-admin")
    @GetMapping("/roomInfo/export")
    public void exportData(@RequestParam(required = false) String name, HttpServletResponse response) throws IOException, IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<RoomDetailInfoResp> roomDetailInfoResp = new ArrayList<>();
        List<Rooms> roomList = roomsService.list();
        List<RoomType> roomTypeList = roomTypeService.list();
        //全部导出
        if(StringUtils.isBlank(name)){
            //查询所有用户
             roomDetailInfoResp = roomTypeService.listAllRoomInfo(roomList, roomTypeList);
        }
        writer.write(roomDetailInfoResp,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("房间信息表","UTF-8")+".xlsx");
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将excel写入到输出流里，并设置用完流之后就关闭
        writer.flush(outputStream,true);
    }

    /**
     * 批量导入
     * @param file
     * @return
     * @throws IOException
     */
    @Operation(summary = "房间管理-导入-admin")
    @PostMapping("/roomInfo/import")
    public Result<ErrorCode> importData(MultipartFile file) throws IOException {
        try {
            //获取inputStream流
            InputStream inputStream  = file.getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            List<RoomDetailInfoResp> list = reader.readAll(RoomDetailInfoResp.class);
            log.info("list:{}",list);
            //Rooms列表
            //ArrayList<Rooms> roomList = new ArrayList<>();
            for (RoomDetailInfoResp roomDetailInfoResp : list) {
                Rooms rooms = new Rooms();
                log.info("roomDetailInfoResp:{}",roomDetailInfoResp);
                rooms.setId(roomDetailInfoResp.getRoomId());
                rooms.setStatus(0);
                String roomName = roomDetailInfoResp.getRoomName();
                int typeId = roomTypeService.roomNameStringToInt(roomName);
                rooms.setTypeId(typeId);
                log.info("typeId:{}",typeId);
                log.info("rooms:{}",rooms);
                //添加到List中
                //roomList.add(rooms);
                //TODO 让roomType表中对应的房间数量加一
                roomTypeService.updateRoomTypeInfoInc(typeId);
                roomsService.save(rooms);
            }
            //log.info("roomList:{}",roomList);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败");
        }
        return Result.success("200",ErrorCode.SUCCESS);
    }

}
